<template>
<div class="adoptAreaPointList">
  <search-block>
    <template slot="button">
      <el-button type="primary" @click="search(true)">查询</el-button>
      <el-button type="primary" @click="addAreaPoint">添加点位</el-button>
      <comments-switch
        comment-business-type="0"></comments-switch>
    </template>
    <el-form inline :model="model" label-width="100px">
      <el-form-item label="点位名:">
        <el-input v-model="model.pointName" clearable></el-input>
      </el-form-item>
      <el-form-item label="所在区域:">
        <el-select v-model="model.areaId" clearable>
          <el-option
            v-for="item in areaOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"></el-option>
        </el-select>
      </el-form-item>
<!--      <el-form-item label="设别供应商:">-->
<!--        <el-select v-model="model.iotType" clearable>-->
<!--          <el-option value="1" label="阿里云"></el-option>-->
<!--          <el-option value="2" label="萤石云"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
    </el-form>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns">
    <el-table-column slot="pointImgUrl" label="点位图片" align="center" header-align="center" width="200">
      <template v-slot="{row}">
        <img v-if="row.pointImgUrl" style="height: 100px" :src="generateMediaUrl({fileOpenUrl: row.pointImgUrl})"/>
      </template>
    </el-table-column>
    <el-table-column slot="enableFlag" label="启用" align="center" header-align="center" min-width="15">
      <template v-slot="{row}">
        <el-popconfirm
            :title="row.enableFlag === '0' ? '是否确认启用该区域？' : '是否确认停用该区域？'"
            @confirm="() => {
              if(row.enableFlag === '0') enableAreaPoint(row)
              else disableAreaPoint(row);
            }">
          <el-switch
            disabled
            slot="reference"
            v-model="row.enableFlag"
            active-value="1"
            inactive-value="0"></el-switch>
        </el-popconfirm>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="150">
      <template v-slot="scope">
        <div class="column-table-buttons">
          <el-button size="mini" @click="showComment(scope.row)">查看评论</el-button>
          <el-button type="primary" size="mini" @click="editAreaPoint(scope.row)">编辑</el-button>
          <el-popconfirm
            title="是否确认删除该点位？"
            @confirm="delAreaPoint(scope.row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <el-dialog
    v-if="commentForms.row"
    :key="commentRefreshKey"
    width="1200px"
    class="force-inner-scroll"
    :visible.sync="commentForms.showForm"
    @closed="commentRefreshKey += 2"
    :title="`点位【${commentForms.row.pointName}】的评论`">
    <comments-info-list
      v-if="commentForms.row && commentForms.row.id"
      :biz-id="commentForms.row.id"
      comment-business-type="0"></comments-info-list>
  </el-dialog>
  <y-form
    ref="form"
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    destroy-on-close
    width="900px"
    :form-attrs="forms.formAttrs"
    :columns="formColumns"
    @ensure="ensureModel">
  </y-form>
</div>
</template>

<script>
import CommentsSwitch from "@/components/Comments/CommentsSwitch";
import CommentsInfoList from "@/components/Comments/CommentsInfoList";
export default {
  name: "adoptAreaPointList",
  inject: ['generateMediaUrl', 'registerCustomEvent'],
  components: { CommentsSwitch, CommentsInfoList },
  computed:{
    getDataWay(){
      return{
        dataType: 'url',
        data: this.$api.adopt.adoptAreaPointList,
        param: this.model
      }
    },
    formColumns(){
      return [
        {
          label: "点位代码",
          prop: "pointCode",
          comp:{
            compType: 'input',
            attrs:{
              disabled: this.forms.formsType === 'EDIT',
              maxlength: 10,
              showWordLimit: true
            }
          }
        },{
          label: "点位名",
          prop: "pointName",
          comp:{
            compType: 'input',
            attrs:{
              maxlength: 30,
              showWordLimit: true
            }
          }
        },{
          label: "所在区域",
          prop: "areaId",
          comp:{
            compType: 'select',
            options: this.areaOptions
          }
        },{
          label: "设备供应商",
          prop: "iotType",
          rules: (function(){
            return !this.forms.formModel.pointVideoUrl ?
              [{required: true, message: "请选择设备供应商", trigger: "change"}] :
              []
          }).call(this),
          comp:{
            compType: 'select',
            options: [{
              label: '阿里云',
              value: '1'
            },{
              label: '萤石云',
              value: '2'
            }],
            attrs:{
              clearable: true
            },
            listeners:{
              change: () => { this.forms.formModel.iotId = '' }
            }
          }
        },{
          label: "直播设备",
          prop: "iotId",
          vIf: !!this.forms.formModel.iotType,
          rules: (function(){
            return !this.forms.formModel.pointVideoUrl ?
              [{required: true, message: "请选择直播设备", trigger: "change"}] :
              []
          }).call(this),
          comp:{
            compType: 'select',
            options: this.forms.formModel.iotType === '1' ? this.iotOptions : this.ysOptions,
            attrs:{
              clearable: true
            }
          }
        },{
          label: "点位图片",
          prop: "pointImgUrl",
          comp:{
            compType: 'YUploadImg',
            attrs:{
              url: this.forms.formModel.pointImgUrl ? [{
                url: this.forms.formModel.pointImgUrl,
                id: this.forms.formModel.pointImgId
              }] : [],
              valueType: "ObjectArray",
              businessSysModuleCode: "ADOPTED_DETAIL_ALBUM",
              limit: 1,
              reUpload: true,
              cropperOptions:{
                fixedNumber: [16, 9]
              }
            },
            listeners:{
              update: this.updateImgModel
            }
          }
        },{
          label: "点位视频",
          prop: "pointVideoUrl",
          rules: (function(){
            return !this.forms.formModel.iotId ?
              [{required: true, message: "请选择点位视频", trigger: "change"}] :
              []
          }).call(this),
          comp:{
            compType: 'YUploadVideoSingle',
            attrs:{
              model: {
                videoAttachmentId: this.forms.formModel.pointVideoId,
                videoName: '',
                videoUrl: this.forms.formModel.pointVideoUrl
              },
              businessSysModuleCode: "ADOPT_AREA_POINT",
              showDelete: true,
              customStyle: {
                display: 'inline-flex'
              }
            },
            listeners:{
              updateExactly: this.updateModel
            }
          }
        },{
          label: "点赞数",
          prop: "likeNo",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true
            }
          }
        },{
          label: "投喂数",
          prop: "feedNo",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true
            }
          }
        },{
          label: "排序",
          prop: "orderNum",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true
            }
          }
        },{
          label: "点位详情",
          prop: "pointDescription",
          comp:{
            compType: 'YRichText'
          }
        }
      ]
    }
  },
  data(){
    return{
      commentRefreshKey: 1,
      model:{
        pointName: '',
        iotType: '',
        areaId: ''
      },
      iotOptions: [],
      ysOptions: [],
      areaOptions: [],
      columns: [{
        label: "点位名",
        prop: "pointName",
        minWidth: 30
      },{
        label: "点位代码",
        prop: "pointCode",
        minWidth: 30
      },{
        label: "所在区域",
        prop: "areaId",
        minWidth: 30,
        formatter: (function(row){
          return this.$$getArrayName(row.areaId, this.areaOptions, {
            label: 'label', value: 'value'
          })
        }).bind(this)
      },{
        label: "设备供应商",
        prop: "iotType",
        minWidth: 30,
        formatter(row){
          if(row.iotType === '1'){ return '阿里云' }
          if(row.iotType === '2'){ return '萤石云' }
          return '';
        }
      },{
        label: "点位图片",
        prop: "pointImgUrl",
        template: true
      },{
        label: "排序",
        prop: "orderNum",
        minWidth: 30
      },{
        label: "启用",
        prop: "enableFlag",
        template: true
      }],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加点位',
          'EDIT': '编辑点位'
        },
        formModel:{
          id: '',
          pointName: '',
          pointCode: '',
          orderNum: '',
          pointDescription: '',
          likeNo: '',
          feedNo: '',
          iotType: '',
          iotId: '',
          areaId: '',
          pointImgId: '',
          pointImgUrl: '',
          pointVideoId: '',
          pointVideoUrl: ''
        },
        currentForm: null,
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            pointName: [{required: true, message: "请输入点位名", trigger: "blur"}],
            pointCode: [
              {required: true, message: "请输入点位代码", trigger: "blur"},
              {
                validator: (rule, value, callback) => {
                  this.$$validateCode(
                    this.$api.adopt.validateAreaCodePoint,
                    {
                      pointCode: value,
                      id: this.forms.formModel.id
                    }, callback);
                },
                trigger: 'blur'
              }
            ],
            areaId: [{required: true, message: "请选择所在区域", trigger: "change"}],
            pointImgUrl: [{required: true, message: "请选择点位图片", trigger: "change"}],
          }
        }
      },
      commentForms:{
        row: {},
        showForm: false,
      }
    }
  },
  created(){ this.initOptions() },
  methods:{
    initOptions(){
      this.registerCustomEvent('refreshAdoptAreaList', 'adoptAreaPointList', this.initAreaOptions);
      this.registerCustomEvent('refreshIotList', 'adoptAreaPointList', this.initIotOptions);
      this.registerCustomEvent('refreshYsList', 'adoptAreaPointList', this.initYsOptions);
      this.initIotOptions();
      this.initYsOptions();
      this.initAreaOptions();
    },
    initIotOptions(){
      this.$yAxios({
        url: this.$api.self.iotArray
      }, info => {
        this.iotOptions = info.map(({id, deviceName}) => ({
          value: id,
          label: deviceName
        }));
      })
    },
    initYsOptions(){
      this.$yAxios({
        url: this.$api.self.ysList
      }, info => {
        this.ysOptions = info.map(({id, name}) => ({
          value: id,
          label: name
        }));
      })
    },
    initAreaOptions(){
      this.$yAxios({
        url: this.$api.adopt.adoptAreaArray
      }, info => {
        this.areaOptions = info.map(({id, areaName}) => ({
          value: id,
          label: areaName
        }));
      })
    },
    resetForm(){
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = this.forms.currentForm ? this.forms.currentForm[key] : '';
      })
    },
    addAreaPoint(){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    search(jumpToFirst){
      this.$refs['table'].loadData(this.model, jumpToFirst);
    },
    showComment(row){
      this.commentForms.row = row;
      this.$nextTick(() => {
        this.commentForms.showForm = true;
      })
    },
    editAreaPoint(row){
      this.forms.formsType = 'EDIT';
      this.forms.currentForm = row;
      this.resetForm();
      this.forms.showForm = true;
    },
    delAreaPoint(row){
      this.$yAxios({
        url: this.$api.adopt.removeAdoptAreaPoint,
        data:{
          ids: [row.id]
        }
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    enableAreaPoint(row){
      this.$yAxios({
        url: this.$api.adopt.enableAreaPoint,
        data:{
          ids: [row.id]
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功启用点位【${row.pointName}】`
        });
        this.search();
      });
    },
    disableAreaPoint(row){
      this.$yAxios({
        url: this.$api.adopt.disableAreaPoint,
        data:{
          ids: [row.id]
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功停用点位【${row.pointName}】`
        });
        this.search();
      });
    },
    ensureModel(form){
      let newForm;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = Object.assign({ enableFlag: '1' }, form);
      }
      this.$yAxios({
        url: this.$api.adopt.saveAdoptAreaPoint,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search(this.forms.formsType === 'ADD');
      })
    },
    updateModel({type, file}){
      switch(type) {
        case 'delete': {
          this.forms.formModel.pointVideoId = '';
          this.forms.formModel.pointVideoUrl = '';
          break;
        }
        case 'add':{
          this.forms.formModel.pointVideoId = file.videoAttachmentId;
          this.forms.formModel.pointVideoUrl = file.videoUrl;
          this.$refs['form'].$refs['form'].validateField('pointVideoUrl');
          break;
        }
      }
    },
    updateImgModel({type, file}){
      switch(type) {
        case 'delete': {
          this.forms.formModel.pointImgId = '';
          this.forms.formModel.pointImgUrl = '';
          break;
        }
        case 'edit': case 'add':{
          this.forms.formModel.pointImgId = file.id;
          this.forms.formModel.pointImgUrl = file.name;
          this.$refs['form'].$refs['form'].validateField('pointImgUrl');
          break;
        }
      }
    },
  }
}
</script>

<style scoped lang="less">
</style>